package com.yinuo.starter.aspect;

import com.alibaba.fastjson.JSON;
import com.yinuo.starter.anno.TransactionalProducer;
import com.yinuo.starter.factory.ProducerFactory;
import com.yinuo.starter.util.TransactionalMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

@Aspect
@Component
@Slf4j
public class ProducerAspect {

    @Autowired(required = false)
    private ProducerFactory producerFactory;


    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Pointcut("@annotation(com.yinuo.starter.anno.TransactionalProducer)")
    public void annotationPoinCut(){}

    @Around("annotationPoinCut() && @annotation(translationProducer)")
    public void around(ProceedingJoinPoint proceedingJoinPoint, TransactionalProducer translationProducer) throws Throwable {
        if(producerFactory == null){
            throw new Exception("yinuo.translation.enabled must be true!");
        }
        Object[] args = proceedingJoinPoint.getArgs();
        TransactionalMessage translationMessage = (TransactionalMessage) args[0];
        if(translationMessage == null ){
            throw new Exception("transactional method first arg must be [TranslationMessage.class]");
        }
        Message message = new Message(translationMessage.getTopicName(), "", translationMessage.getId(),
                JSON.toJSONString(translationMessage).getBytes());
        TransactionSendResult sendResult = producerFactory.getProducer().sendMessageInTransaction(message, proceedingJoinPoint);
        if(sendResult.getSendStatus() == SendStatus.SEND_OK){
            log.info("MQ SEND STATUS:  {}", "message send success!");
        }else{
            log.error("MQ SEND STATUS:  {}", "message send fail!");
        }
    }

}
